<template>
    <van-address-list 
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="AddressAdd"
        @edit="AddressEdit"
        @select="AddressSelect"
    />
</template>

<script setup>
    const {proxy} = getCurrentInstance()

    let business = proxy.$business
    
    let active = ref(1)

    //收获地址列表
    let list = ref([])

    //收获地址添加
    const AddressAdd = async () => proxy.$router.push('/address/add')

    //收获地址的编辑
    const AddressEdit = async (item) => proxy.$router.push({path: '/address/edit', query: {id: item.id}})

    //钩子函数
    onMounted(() => {
        Address()
    })

    //获取列表
    const Address = async () => 
    {
        var result = await proxy.$POST({url: '/address/index', params: {busid: business.value.id}})

        if(result.code == 0) return proxy.$fail(result.msg)

        var temp = []

        for(var item of result.data)
        {
            if(item.status == '1') active.value = item.id

            temp.push({
                id: item.id,
                name: item.consignee,
                tel: item.mobile,
                address: `${item.region_text} ${item.address}`,
                isDefault: item.status == '1' ? true : false
            })
        }
        
        list.value = temp
    }

    //切换默认地址
    const AddressSelect = async (item, key) =>
    {
        //组装数据
        var params = {
            busid: business.value.id,
            id: item.id
        }

        var result = await proxy.$POST({url: '/address/check', params})

        if(result.code == 0) return proxy.$fail(result.msg)

        //默认将所有的数据全部设置为false
        list.value.map((item) => item.isDefault = false)

        // 在给指定的记录 修改为 true
        list.value[key].isDefault = true
    }
</script>